package cn.itsource.shop.controller;

import cn.itsource.basic.util.ExcelUtil;
import cn.itsource.shop.service.IShopService;
import cn.itsource.shop.domain.Shop;
import cn.itsource.shop.query.ShopQuery;
import cn.itsource.basic.util.AjaxResult;
import cn.itsource.basic.page.PageList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.mail.MessagingException;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/shop")
public class ShopController {
    @Autowired
    public IShopService shopService;


    /**
     * 保存和修改公用的
     * @param shop  传递的实体
     * @return Ajaxresult转换结果
     */
    @PutMapping
    public AjaxResult addOrUpdate(@RequestBody Shop shop){
            if( shop.getId()!=null)
                shopService.update(shop);
            else
                shopService.insert(shop);
            return AjaxResult.me();
    }
    /**
    * 删除对象信息
    * @param id
    * @return
    */
    @DeleteMapping(value="/{id}")
    public AjaxResult delete(@PathVariable("id") Long id){
        try {
            shopService.delete(id);
            return AjaxResult.me();
        } catch (Exception e) {
        e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("删除对象失败！"+e.getMessage());
        }
    }
	
    //获取用户
    @GetMapping("/{id}")
    public Shop get(@PathVariable("id")Long id)
    {
        return shopService.findOne(id);
    }


    /**
    * 查看所有的员工信息
    * @return
    */
    @GetMapping()
    public List<Shop> list(){

        return shopService.findAll();
    }


    /**
    * 分页查询数据
    *
    * @param query 查询对象
    * @return PageList 分页对象
    */
    @PostMapping("/list")
    public PageList<Shop> json(@RequestBody ShopQuery query)
    {
        return shopService.pageQuery(query);
    }

    @PostMapping("/settlement")
    public AjaxResult settlement(@RequestBody @Valid Shop shop){
        return shopService.settlement(shop);
    }

    @PostMapping("/audit")
    public AjaxResult audit(@RequestBody Map<String,Object> map){
        try {
            return shopService.audit(map);
        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
    }

    @GetMapping("/export")
    public void export(HttpServletResponse response){
        //所有店铺数据
        List<Shop> all = shopService.findAll();

        ExcelUtil.exportExcel(all,null,null, Shop.class,"shop.xls",response);
    }

    @PostMapping("/import")
    public void importExcel(@RequestPart MultipartFile file){

        List<Shop> shops = ExcelUtil.importExcel(file, 0, 1, Shop.class);

        shops.forEach(System.out::println);
    }
}
